import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userInfoApi, permRangeApi } from '../../api/user'
import { constantRoutes, resetRouter } from '../../router'

// 用户模块 token setToken removeToken
export const useUserStore = defineStore(
  'admin-user',
  () => {
    const token = ref('')
    const setToken = (newToken) => {
      token.value = newToken
    }
    const removeToken = () => {
      token.value = ''
    }

    const userInfo = ref({})
    const setUserInfo = async () => {
      // 设置userInfo
      const res = await userInfoApi()
      userInfo.value = res.data
    }

    // 权限
    const setPermRange = async () => {
      const res = await permRangeApi()
      userInfo.value.permRange = res.data
      return res.data
    }

    // 登出
    const logout = () => {
      token.value = ''
      userInfo.value = ''

      // 重置路由
      resetRouter()
    }

    // 路由
    const routes = ref(constantRoutes)
    const setRoutes = (asynchrousRoutes) => {
      routes.value = [...constantRoutes, ...asynchrousRoutes]
    }

    return {
      token,
      setToken,
      removeToken,
      userInfo,
      setUserInfo,
      logout,
      routes,
      setRoutes,
      setPermRange
    }
  },
  {
    persist: {
      paths: ['token']
    }
  }
)
